package edu.ynu.se.xiecheng.achitectureclass.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.entity.vo.Result;
import edu.ynu.se.xiecheng.achitectureclass.mapper.UserMapper;
import edu.ynu.se.xiecheng.achitectureclass.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author laruui
 * @since 2023-12-07
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public Result login(User user) {
        try {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>()
                    .eq(User::getAccount, user.getAccount());
            // 查询得到的对象
            User selectUser = userMapper.selectOne(userLambdaQueryWrapper);
            // 如果未查询到用户
            if (selectUser == null) {
                return Result.builder().code(500).message("账号或密码错误！").build();
            }
            // 如果密码为空
            if (user.getPassword() == null) {
                return Result.builder().code(500).message("密码不能空！").build();
            }
            // 加密密码
            String md5password = DigestUtils.md5Hex(user.getPassword());
            // 如果加密后的密码和数据库种的密码比对不正确
            if (!(md5password.equals(selectUser.getPassword()))) {
                return Result.builder().code(500).message("密码错误！").build();
            }
            // 返回给前端一个简易token
            Map<String, Object> token = new HashMap<>();
            token.put("token", selectUser);
            return Result.builder().code(200).message("登陆成功！").data(token).build();
        } catch (Exception e) {
            log.info("出现异常！");
            return Result.builder().code(500).message("系统故障").build();
        }
    }

    @Override
    public Result logout() {
        return Result.builder().code(200).message("登出成功！").build();
    }

    @Override
    public Result getLoginUserInfo(String token) {
        User user = JSON.parseObject(token, User.class);
        Map<String, String> userInfo = new HashMap<>();
        userInfo.put("account", user.getAccount());
        userInfo.put("name", user.getNikname());
        userInfo.put("role", user.getFlag());
        userInfo.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        return Result.builder().code(200).message("登陆成功").data(userInfo).build();
    }
}
